import os
import shutil

from flask import Flask, render_template, jsonify, request
from flask_uploads import UploadSet, configure_uploads, TEXT
import pymysql
import traceback
import requests
import json
from datetime import datetime

app = Flask(__name__)
# 配置上传文件保存目录
app.config['UPLOADED_FILES_DEST'] = '/mnt/sda0/Public/Download'
app.config['UPLOADED_FILES_ALLOW'] = ['txt', 'jsoon']
# 初始化UploadSet对象
files = UploadSet(name='files', extensions=TEXT)
# 将Flask app与UploadSet对象进行绑定
configure_uploads(app, files)


@app.route('/', methods=['POST'])
def upload_file():
    file = request.files['file']
    filename = files.save(file)
    return jsonify({'code': 200})


@app.route('/json', methods=['POST'])
def upload_json_file():
    file = request.files['file']
    filename = files.save(file)
    shutil.copy2(filename, request.form.get("file_name"))
    os.remove(filename)
    return jsonify({'code': 200})


@app.route("/push/demo")
def pushDemo():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        with conn.cursor() as c:
            c.execute(f"select * from history order by created desc limit 5")
            datas = c.fetchall()
            history = []
            for da in datas:
                history.append(da[1].strftime("%Y-%m-%d %H:%M:%S"))
            c.execute(f"select battery,time from battery where userid=90")
            b_data = c.fetchone()
            battery = b_data[0]
            time = b_data[1]
            c.close()
            return render_template("push_demo.html", data=history, bTime=time.strftime("%Y-%m-%d %H:%M:%S"),
                                   battery=battery)
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route("/push/action")
def pushAction():
    try:
        pushHeaders = {
            'Content-Type': 'application/json',
            'Authorization': 'Basic MmFkYTFlZWQ1NjQyMTcxOTkyMTUwYjkyOmNmYTc1MTE3Y2UwYjYxMmRiMGE5ZDhiOA=='
        }

        result = requests.get('https://api.jpush.cn/v3/push/cid', headers=pushHeaders).json()
        cid = result['cidlist'][0]
        actionType = request.args.get("type")
        jsonData = {"cid": cid, "platform": "all", "audience": {"alias": ["666"]},
                    "message": {"msg_content": actionType, "content_type": actionType},
                    "options": {"time_to_live": 60, "apns_production": True}}

        result = requests.post('https://api.jpush.cn/v3/push', headers=pushHeaders, json=jsonData).json()
        return f"push action success ：{result}"

    except:
        print(traceback.format_exc())
        return f"push action error {traceback.format_exc()}"


@app.route('/push/success')
def pushSuccess():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        userid = request.args.get("userid")
        with conn.cursor() as c:
            c.execute(f"insert into history(userid) values({userid})")
            conn.commit()
            c.close()
        return jsonify({'code': 200})
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route("/push/latest")
def pushLatest():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        with conn.cursor() as c:
            c.execute(f"select created from history order by created desc")
            last = c.fetchone()
            c.close()
            nowHour = datetime.now().hour
            am = [8, 9, 10, 11, 12]
            fm = [18, 19, 20, 21]
            if nowHour in am:
                if last[0].hour in fm:
                    requests.get(
                        "https://sctapi.ftqq.com/SCT217072TdGJyyWlRZQwsFiiYaK4lJ7ru.send?title=You forgot push AM "
                        "message.")
                else:
                    print('has ding')
            else:
                if last[0].hour in am:
                    requests.get(
                        "https://sctapi.ftqq.com/SCT217072TdGJyyWlRZQwsFiiYaK4lJ7ru.send?title=You forgot push PM "
                        "message.")
                else:
                    print('has ding')

        return f"success {last}"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


@app.route('/push/battery')
def pushBattery():
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='zR@Dew4!FdcUE:k', db='ding')
    try:
        battery = request.args.get("battery")
        userid = request.args.get("userid")
        with conn.cursor() as c:
            c.execute(
                f"insert into battery(userid, battery) values ({userid}, {battery}) on duplicate key update battery=values(battery)")
            conn.commit()
            c.close()
        return "success"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()

@app.route('/fang/search')
def focusHouse():
    conn = pymysql.connect(host='82.156.52.41', port=23306, user='root', passwd='zR@Dew4!FdcUE:k', db='fang')
    try:
        id = request.args.get("house_id")
        with conn.cursor() as c:
            c.execute(f"select * from focus_house where house_id={id}")
            houses = c.fetchall()
            c.close()
            list = []
            detail = f'https://bj.ke.com/ershoufang/{id}.html'
            for house in houses:
                list.append({'time':house[8].strftime('%Y-%m-%d'),'price':house[3]})
            print(list)
            return render_template("focus_house.html",data=list,detail=detail)
        return "success"
    except:
        print(traceback.format_exc())
        return "error"
    finally:
        conn.close()


if __name__ == '__main__':
    app.run(port=7070)
